package it.hive.controller.task;

import javafx.animation.FadeTransition;
import javafx.beans.property.SimpleStringProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.util.Duration;

public class Animazione {
	private static FadeTransition fadeout;

	public static void avviaAnimazione(Node node) {
		avviaAnimazione(node, 3);
	}

	public static void avviaAnimazione(Node node, int second) {
		avviaAnimazione(node, second, true);

	}

	public static void avviaAnimazione(final Node node, int second, final boolean hide) {
		fadeout = new FadeTransition(Duration.seconds(second), node);
		fadeout.setFromValue(1.0);
		fadeout.setToValue(0);
		fadeout.onFinishedProperty().set(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent actionEvent) {
				if (hide) {
					node.setOpacity(1);
					if (!node.visibleProperty().isBound()) {
						node.setVisible(false);
					}
				}
			}
		});
		fadeout.play();
	}

	public static void switchAnimazione(final Node start, final Node end, final int second) {
		if (!start.isVisible()) {
			if (!start.visibleProperty().isBound()) {
				start.setVisible(true);
			}
			start.setOpacity(1);
		}
		if (end.isVisible()) {
			if (!end.visibleProperty().isBound()) {
				start.setVisible(false);
			}
		}
		fadeout = new FadeTransition(Duration.seconds(second / 2), start);
		fadeout.setFromValue(1.0);
		fadeout.setToValue(0);
		fadeout.onFinishedProperty().set(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent actionEvent) {
				start.setOpacity(1);
				if (!start.visibleProperty().isBound()) {
					start.setVisible(false);
				}
				if (!end.isVisible()) {
					if (!end.visibleProperty().isBound()) {
						end.setVisible(true);
					}
				}
				FadeTransition endNodo = new FadeTransition(Duration.seconds(second / 2), end);
				endNodo.setFromValue(0);
				endNodo.setToValue(1);
				endNodo.play();
			}
		});
		fadeout.play();
	}

	public static synchronized Thread animazioneTesto(final SimpleStringProperty prop, final String newText) {
		Thread t = new Thread() {
			String oldValue;

			@Override
			public void run() {
				oldValue = prop.get() != null ? prop.get() : "";
				for (int i = oldValue.length(); i != 0; i--) {
					prop.set(oldValue.substring(0, i));
					try {
						Thread.sleep(15);
					} catch (InterruptedException e) {
					}
				}
				for (int i = 0; i <= newText.length(); i++) {
					prop.set(newText.substring(0, i));
					try {
						Thread.sleep(15);
					} catch (InterruptedException e) {
					}
				}
			}
		};
		t.start();
		return t;

	}
}
